// 获取当前的商品的ID
let goodsId = yzb.getUrlValue('goodsId');
let catId = yzb.getUrlValue('catId');
let catName = yzb.getUrlValue('catName');

// 面包屑导航
let oNowBreadcrumb = document.querySelector('.now-breadcrumb');
oNowBreadcrumb.innerHTML = CAT_DATA.filter(item => item.cat_id == catId)[0].cat_name;
let oGoodsContent = document.querySelector('.goods-content');

// 请求数据
yzb.ajax({
	url: BASE_URL + "/api_goods",
	data: {
		goodsId
	},
	success(res) {
		if (res.code != 0) {
			console.log(res);
			return;
		};
		// 验证商品有没有
		if (res.data.length == 0) {
			oGoodsContent.innerHTML == '此商品已下架...';
			return;
		};
		// 获取商品
		let goods = res.data[0];
		// 获取轮播
		let goodsBanner = goods.banner;

		// 商品详情图片
		let productBanner = goods.product_banner;



		// 调用渲染放大镜的方法
		glassRender(goodsBanner);

		// 调用渲染中间商品详情的方法
		productRightRender(goods);

		// 详情渲染之后 改中间详情图片数据
		let oBrandColor = document.querySelector('.brand-color');
		let strColor = '';
		goodsBanner.forEach(item => {
			strColor += `
		<p>
			<img src="${item}" />
		</p>
			`;
		});
		// 添加到结构
		oBrandColor.innerHTML = strColor;
		// 设置图片盒子高
		let aBrandP = document.querySelectorAll('.brand-color p');
		pWidth = aBrandP[0].offsetWidth;
		if ((pWidth * aBrandP.length) >= 280) {
			oBrandColor.style.height = pWidth * 2 + 'px';
		} else {
			oBrandColor.style.height = pWidth + 'px';
		}

		// 点击图片
		for (let i = 0; i < aBrandP.length; i++) {
			aBrandP[i].onclick = function() {
				for (let j = 0; j < aBrandP.length; j++) {
					aBrandP[j].style.border = '1px solid transparent';
				};
				aBrandP[i].style.border = '1px solid #333';
			}
		}

		// 图片详情介绍
		let oGoodsContentImg = document.querySelector('.goods-contentImg');
		let strGoodsImg = '';
		productBanner.forEach(item => {
			strGoodsImg += `
			<img src="${item}" />
			`;
		});
		oGoodsContentImg.innerHTML = strGoodsImg;

		// 品牌简介
		let oBrandDescribe = document.querySelector('.brand-describe');
		let brandStr = '';
		res.data.forEach(item => {
			brandStr += goods.lc_recommend;
		})
		// 添加到页面
		oBrandDescribe.innerHTML = brandStr;
		productSwiper()


		// 售后须知
		let oSeviceBtn = document.querySelector(".seviceBtn");
		let oTips = document.querySelector(".tips");

		oSeviceBtn.onmouseenter = function() {
			oTips.style.display = "block";
		};

		oSeviceBtn.onmouseleave = function() {
			oTips.style.display = "none";
		};

		// 调用随机猜你喜欢方法
		likeRandom();
	},
})

// 封装放大镜渲染的方法
function glassRender(data) {
	// 放大镜的父级
	let oGoodsLcontent = document.querySelector('.goods-lcontent');
	let oSmallImg = document.querySelector('.small-img');
	let oSlide = document.querySelector('.slide');
	let oBigImg = document.querySelector('.big-img');
	// 操作dom

	// 上面列表
	let oListimg = document.querySelector('.list-img');

	// 上面列表渲染
	let strUp = '';
	data.forEach(item => {
		strUp += `
		<li>
			<a href=""><img src="${item}" class="small-img"/></a>
		</li>
		`;
	})
	oListimg.innerHTML = strUp;

	// 下面列表
	let oBoxList = document.querySelector('.box-list');

	// 下面列表渲染
	let str = '';
	data.forEach(item => {
		str += `
		<li>
			<a><img src="${item}" /></a>
		</li>
		`;
	});


	// 添加至页面
	oBoxList.innerHTML = str;


	// 设置下面列表的宽度
	let aLi = document.querySelectorAll('.box-list li');
	let liW = aLi[0].offsetWidth + parseInt(getComputedStyle(aLi[0])['marginRight']);


	// 设置ul宽度
	oBoxList.style.width = aLi.length * liW + "px";
	let oBox = document.querySelector('.goods-img');
	let oBig = document.querySelector('.goods-glass');

	// 放大镜
	oGoodsLcontent.onmouseover = function() {
		oSlide.style.display = 'block';
	};
	oGoodsLcontent.onmousemove = function(e) {

		oBig.style.display = "block";
		// 设定没有误差的值
		let l = e.clientX - oSlide.offsetWidth / 2 - oBox.getBoundingClientRect().left;
		let t = e.clientY - oSlide.offsetHeight / 2 - oBox.getBoundingClientRect().top;
		if (l <= 0) l = 0;
		if (t <= 0) t = 0;
		let maxXy = oBox.clientWidth - oSlide.offsetWidth;
		if (l >= maxXy) l = maxXy;
		if (t >= maxXy) t = maxXy;
		// 滑块移动
		oSlide.style.left = l + 'px';
		oSlide.style.top = t + 'px';
		let bili = (oBigImg.offsetWidth - oBig.clientWidth) / (oBox.clientWidth - oSlide.offsetWidth);
		oBigImg.style.left = -bili * l + "px";
		oBigImg.style.top = -bili * t + "px";
	};

	oGoodsLcontent.onmouseout = function() {
		oSlide.style.display = 'none';
		oBig.style.display = "none";
	};

	// 设置放大镜大图路径
	oBigImg.src = data[0];
};

// 商品详情图片轮播方法
function productSwiper() {
	let ogImg = document.getElementById("goods-img");
	let olImg = ogImg.getElementsByTagName("ul")[0];
	let aliImg = olImg.getElementsByTagName("li");
	let oBigImg = document.querySelector('.big-img');

	let oBul = document.getElementById("box-list");
	let aliBox = oBul.getElementsByTagName("li");
	// console.log(aliBox);

	let oLa = document.getElementById("left-arrow");
	let oRa = document.getElementById("right-arrow");
	// 克隆第一张至末尾
	olImg.appendChild(aliImg[0].cloneNode(true));
	// 设置上面列表的宽
	olImg.style.width = aliImg[0].offsetWidth * aliImg.length + "px";
	// 上一页一开始隐藏
	oLa.style.display = 'none';

	// 下面列表的li的宽
	let liWDown = aliBox[0].offsetWidth;

	// 信号量
	let n = 0;
	let m = 0;
	// 节流
	let lock = false;
	// 下一张
	oRa.onclick = function() {
		if (lock) return;
		lock = true;
		n++;
		m++;
		m = m > aliBox.length - 1 ? 0 : m;

		// 开启上一张
		oLa.style.display = 'block';
		olImg.style.transition = ".5s";
		olImg.style.left = n * (-350) + "px";
		for (let i = 0; i <= aliBox.length - 1; i++) {
			aliBox[i].style.border = "none";
		}
		aliBox[m].style.border = "1px solid #333";

		// 切换三张之后下一张的位置平移至第一张位置
		if (aliBox.length <= 3) {
			return;
		};
		if (m % 3 == 0) {
			oBul.style.transition = '.5s';
			oBul.style.left = -(m * liWDown) + "px";
		};
		if (m >= aliBox.length - 1) {
			// 禁用下一张
			oRa.style.display = 'none';
		}
	}

	// 上一张
	oLa.onclick = function() {
		if (lock) return;
		lock = true;
		n--;
		m--;
		m = m < 0 ? aliBox.length - 1 : m;
		// 开启下一张
		oRa.style.display = 'block';
		if (n < 0) {
			n = aliImg.length - 1;
			olImg.style.transition = "none";
			olImg.style.left = aliImg.length * -350 + "px";
			n--;
		}
		setTimeout(function() {
			olImg.style.transition = ".5s";
			olImg.style.left = n * -350 + "px";
		})
		for (let i = 0; i <= aliBox.length - 1; i++) {
			aliBox[i].style.border = "none";
		}
		aliBox[m].style.border = "1px solid #333";

		// 按上一张时 大于三张后每一张都在最后一张位置
		// if (aliBox.length <= 4) {
		// 	return;
		// };
		let oIndex = m % aliBox.length;
		if (oIndex <= aliBox.length) {
			oBul.style.left = -(oIndex * liWDown) + "px";
		};
		if (m <= 0) {
			// 禁用上一张
			oLa.style.display = 'none';
		}
	}

	// 监听完成动画
	olImg.ontransitionend = function() {
		lock = false;
		if (n >= aliImg.length - 1) {
			n = 0;
			olImg.style.transition = "none";
			olImg.style.left = 0 + "px";
		}
	}

	// 下面的图片切换
	for (let i = 0; i <= aliBox.length - 1; i++) {

		aliBox[i].onclick = function() {
			// console.log(this)
			if (lock) return;
			lock = true;
			m = i
			n = m
			n = n > aliBox.length - 1 ? 0 : n;
			olImg.style.transition = ".5s";
			olImg.style.left = n * -350 + "px";
			for (let i = 0; i <= aliBox.length - 1; i++) {
				aliBox[i].style.border = "none";

			}
			aliBox[n].style.border = "1px solid #333";
			// console.log(this.querySelector("a").querySelector("img").src);
			oBigImg.src = this.querySelector("a").querySelector("img").src;
		}
	}
};

// 渲染中间商品详情的方法
function productRightRender(data) {
	let oMiddleBrand = document.querySelector('.middle-brand');
	oMiddleBrand.innerHTML = `
	<div class="star">
		<span class="iconfont icon-aixin_shixin"></span>
		<span>${data.star_number}</span>
	</div>
	<div class="brand"><a href="">${data.brand_name}</a></div>
	<div class="goods-name">${data.goods_name}</div>
	<div class="price">
		<span>价格:</span>
		<span>￥${data.price}元</span>
	</div>
	<div>
		<span>免运费</span>
		<span>正品授权</span>
	</div>
	<div class="brand-color">
		<span>规格:</span>
	</div>
	<div>
		<span>数量:</span>
		<img src="img/reduce-g.png" class='reduce'/>
		<input type="text" value="1" readonly class='goods-count'/>
		<img src="img/add-g.png" class='add'/>
	</div>
	<div>
		<button class='now-buy'>立即购买</button>
	</div>
	<div>
		<a class='add-cart-btn'>加入购物车</a>
		<a href="">分享</a>
	</div>
	`;

	let oReduce = document.querySelector('.reduce');
	let oAdd = document.querySelector('.add');
	let oNowBuy = document.querySelector('.now-buy');
	let oAddCartBtn = document.querySelector('.add-cart-btn');
	let oGoodsCount = document.querySelector('.goods-count');

	// 先设置一次数量
	let num = 1;
	oGoodsCount.value = num;

	// 减
	oReduce.onclick = function() {
		num = --num <= 1 ? 1 : num;
		oGoodsCount.value = num;
	};
	// 加
	oAdd.onclick = function() {
		num = ++num >= 10 ? 10 : num;
		oGoodsCount.value = num;
	};

	// 点击立即购买
	oNowBuy.onclick = function() {
		let UASERNAME = localStorage.getItem('username');
		let TOKEN = localStorage.getItem('token');
		// 校验登录状态
		if (!USERNAME || !TOKEN) {
			alert('请先登录');
			return;
		};

		// 先加入结算清单 跳转到订单页面
		yzb.ajax({
			method:'post',
			url:BASE_URL + '/api_settlement',
			data:{
				status:'addsettlement',
				userId:localStorage.getItem('token'),
				from:'product',
				goodsId,
				goodsNumber:num
			},
			success(res){
				if(res.code != 0){
					console.log(res);
					return;
				};
				// 加入结算成功
				alert('加入结算成功');
				// 跳转到订单页面
				location.href = 'order.html';
			}
		})

	};

	// 点击加入购物车
	oAddCartBtn.onclick = function() {
		let UASERNAME = localStorage.getItem('username');
		let TOKEN = localStorage.getItem('token');
		// 校验登录状态
		if (!USERNAME || !TOKEN) {
			alert('请先登录');
			return;
		};

		// 加入
		yzb.ajax({
			method: 'post',
			url: BASE_URL + '/api_cart',
			data: {
				status: 'addcart',
				goodsId,
				userId: TOKEN,
				goodsNumber: num
			},
			success(res) {
				if (res.code != 0) {
					console.log(res);
					return;
				};
				alert('加入购物车成功');
				// 调用头部的购物车方法
				getCartValue();
			}
		})

	};
};


// 随机猜你喜欢方法
function likeRandom() {

	// 请求数据
	yzb.ajax({
		url: BASE_URL + '/api_goods',
		data: {
			catId
		},
		success(res) {
			if (res.code != 0) {
				console.log(res);
				return;
			};
			let oLikeList = document.querySelector('.like-list');
			let dataLike = res.data;
			let arrLike = [];
			let index = 0;
			// 随机四个
			while (arrLike.length < 4) {
				let index = parseInt(Math.random() * dataLike.length);
				if (!arrLike.includes(dataLike[index])) {
					arrLike.push(dataLike[index]);
				}
			};
			arrLike.forEach(item => {
				let li = document.createElement("li");
				li.innerHTML = `
			<img src="${item.goods_thumb}" />
						<p>${item.goods_name}</p>
						<p>${item.brand_name}</p>
						<p>
							<span>￥${item.price}</span>
							<span>￥${(item.price / 0.9).toFixed(2)}</span>
						</p>
			`;
				// 添加结构
				oLikeList.appendChild(li);
			})
			// 换一批
			let oChange = document.querySelector('.changeImg');
			oChange.onclick = function() {
				oLikeList.innerHTML = '';
				let dataLike = res.data;
				let arrLike = [];
				let index = 0;
				// 随机四个
				while (arrLike.length < 4) {
					let index = parseInt(Math.random() * dataLike.length);
					if (!arrLike.includes(dataLike[index])) {
						arrLike.push(dataLike[index]);
					}
				};
				arrLike.forEach(item => {
					let li = document.createElement("li");
					li.innerHTML = `
				<img src="${item.goods_thumb}" />
							<p>${item.goods_name}</p>
							<p>${item.brand_name}</p>
							<p>
								<span>￥${item.price}</span>
								<span>￥${(item.price / 0.9).toFixed(2)}</span>
							</p>
				`;
					// 添加结构
					oLikeList.appendChild(li);
				})
			}
		}
	})
};